package com.xz.knowledgeDuplication.juc.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * synchronize与lock区别
 *
 * synchronize内置的java关键字; lock是一个java类
 * synchronize无法判断获取锁的状态; lock可以判断是否获取到了锁
 * synchronize会自动释放锁; lock必须要手动释放锁!如果不释放锁,死锁
 * synchronize线程1(获取锁,阻塞)、线程2(等待,一直等); lock不一定会等待下去
 * synchronize可重入锁,不可以中断的,非公平; lock可重入锁,可以判断,非公平(可自己设置)
 * synchronize适合锁少量的代码同步问题; lock适合锁大量的代码同步问题
 *
 * @author 召
 * @date 2022-08-08 21:51:48
 */
public class SellTicket {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                ticket.sell();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                ticket.sell();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                ticket.sell();
            }
        }, "C").start();
    }

}

class Ticket {

    private int number = 30;

    private Lock lock = new ReentrantLock();

    public void sell() {
        lock.lock();
        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出第" + number-- + "张票,剩余" + number + "张");
            }
        } finally {
            lock.unlock();
        }
    }
}